package com.clouddot.baipai.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.model.beam.getClassInfo.getClassInfoResponse;
import com.clouddot.baipai.model.beam.getClassType.getClassTypeResponse;
import com.clouddot.baipai.model.beam.login.loginResponse;
import com.clouddot.baipai.ui.adapter.H_Adapter.OnDoubleClickListener;
import com.clouddot.baipai.ui.dialog.H_Dialog.H_SettingDailog;
import com.clouddot.baipai.ui.dialog.V_Dialog.V_UpdateDailog;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_ApplyLeaveFragment;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_AttendableFragment;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_ClassFragment;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_HomeFragment;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_HomeWorkFragment;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_MineFragment;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_NewsFragment;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_PRaiseFragment;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_SchoolFragment;
import com.clouddot.baipai.ui.fragment.V_MainFragment.V_TableableFragment;
import com.clouddot.baipai.ui.util.Ftp.DownFileUtil;
import com.clouddot.baipai.ui.util.SelectedBtnUtil;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPool;
import com.clouddot.baipai.ui.util.getTimeAndWeatherUtil;
import com.clouddot.baipai.ui.util.ToastUtil;

import org.dom4j.DocumentException;

import java.util.List;
import java.util.Map;

import android_serialport_api.sample.SerialPortActivity;

import static com.clouddot.baipai.ui.activity.H_SMainActivity.MSG_SIX;

/**
 * Created by wxy on 2018/5/7.
 */

public class V_MainActivity extends SerialPortActivity implements View.OnClickListener {
        static {
            System.loadLibrary("serial_port");

    }
    public static  int backTime = -1; //返回主界面时间 ，10秒
    private ImageView left, right;
    private HorizontalScrollView scrollView;
    private TextView Tvtime, Tvdate, Tvweather, classInfo, className, loginTime;
    private LinearLayout linearLayout1, linearLayout2, linearLayout3, linearLayout4, linearLayout5,
            linearLayout6, linearLayout7, linearLayout8, linearLayout9, linearLayout10,linearLayout11;
    private LinearLayout[] linearLayouts = new LinearLayout[10];
    private ImageView img1, img2, img3, img4, img5, img6, img7, img8, img9, img10,img11;
    private ImageView[] imageViews = new ImageView[10];
    private Animation animation;
    private ConstraintLayout top;
    private Fragment[] fragments = new Fragment[10];

    private int currentShowFragmentIndex = 0;//当前的fragment页面的记录号码

    private boolean isScanCard = false; //刷卡机制是否在通讯

    private int time = -1; //登录的剩余时间 ，登录时90秒
    private LoginThread loginThread; // 每秒刷新登录剩下时间
    private BackMainThread backMainThread; //返回主界面 ;
    private boolean isActivity = false; //当前有没有离开activity
    private ModleThread modleThread; // 更新设备模式
    private  Thread TimeThread;
    private View view;
    private boolean isLockSet = false;
    private boolean isLock = true;

    private String cityName;
    private List<Map<String, String>> mapList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        Environment.getInstance().activities.add(this);


        if(TimeThread == null) {
            TimeThread = new Thread(getTimeBySecond);
            TimeThread.start();
        }

        if (Env.getAppContext().isInitial) {
            modleThread = new ModleThread();
            loginThread = new LoginThread();
            backMainThread = new BackMainThread();
            modleThread.start();
            loginThread.start();
            backMainThread.start();
        } else {
            ToastUtil.showToast(this, "还没有设置端口号，请双击顶部栏去到设置界面");
        }
    }

    @Override
    protected void setContentView() {
        super.setContentView();
        setContentView(R.layout.v_a_main);
    }

    @Override
    protected void initControls() {
        super.initControls();

        top = find(R.id.top);

        left = find(R.id.left);
        right = find(R.id.right);
        scrollView = find(R.id.scrollView);

        Tvtime = find(R.id.time);
        Tvdate = find(R.id.date);
        Tvweather = find(R.id.weather);
        className = find(R.id.className);
//        classInfo = find(R.id.classInfo);

        linearLayout1 = find(R.id.home);
        linearLayout2 = find(R.id.home1);
        linearLayout3 = find(R.id.home2);
        linearLayout4 = find(R.id.home3);
        linearLayout6 = find(R.id.home5);
        linearLayout7 = find(R.id.home6);
        linearLayout8 = find(R.id.home7);
        linearLayout9 = find(R.id.home8);
        linearLayout10 = find(R.id.home9);
        linearLayout11 = find(R.id.home10);

        linearLayouts[0] = linearLayout1;
        linearLayouts[1] = linearLayout2;
        linearLayouts[2] = linearLayout3;
        linearLayouts[3] = linearLayout4;
        linearLayouts[4] = linearLayout6;
        linearLayouts[5] = linearLayout7;
        linearLayouts[6] = linearLayout8;
        linearLayouts[7] = linearLayout9;
        linearLayouts[8] = linearLayout10;
        linearLayouts[9] = linearLayout11;

        img1 = find(R.id.img1);
        img2 = find(R.id.img2);
        img3 = find(R.id.img3);
        img4 = find(R.id.img4);
        img6 = find(R.id.img6);
        img7 = find(R.id.img7);
        img8 = find(R.id.img8);
        img9 = find(R.id.img9);
        img10 = find(R.id.img10);
        img11 = find(R.id.img11);

        imageViews[0] = img1;
        imageViews[1] = img2;
        imageViews[2] = img3;
        imageViews[3] = img4;
        imageViews[4] = img6;
        imageViews[5] = img7;
        imageViews[6] = img8;
        imageViews[7] = img9;
        imageViews[8] = img10;
        imageViews[9] = img11;

        fragments[0] = new V_HomeFragment();
        fragments[1] = new V_SchoolFragment();
        fragments[2] = new V_ClassFragment();
        fragments[3] = new V_NewsFragment();
        fragments[4] = new V_TableableFragment();
        fragments[5] = new V_AttendableFragment();
        fragments[6] = new V_HomeWorkFragment();
        fragments[7] = new V_MineFragment();
        fragments[8] = new V_ApplyLeaveFragment();
        fragments[9] = new V_PRaiseFragment();

        animation = AnimationUtils.loadAnimation(V_MainActivity.this, R.anim.buttom_click_anim);

        animation.setDuration(200);
//        startAnim();

        view = getWindow().getDecorView();
        loginTime = find(R.id.lodinTime);
    }

    @Override
    protected void setListener() {
        super.setListener();
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scrollView.arrowScroll(view.FOCUS_LEFT);
            }
        });
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scrollView.arrowScroll(view.FOCUS_RIGHT);

            }
        });

        for (LinearLayout linearLayout : linearLayouts) linearLayout.setOnClickListener(this);

        top.setOnTouchListener(onDoubleClickListener);

        view.setOnSystemUiVisibilityChangeListener
                (new View.OnSystemUiVisibilityChangeListener() {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                            if (!isLockSet) {
                                handler.sendEmptyMessage(H_SMainActivity.MSG_THREE);
                            }
                        } else {
                        }
                    }
                });

    }

    @Override
    protected void onResume() {
        super.onResume();
        handler.sendEmptyMessage(H_SMainActivity.MSG_THREE);
        isActivity = false;
        if (Env.getAppContext().isInitial) {
            runThreadAction();      //获取天气预报
            runThreadAction("getClassInfo"); //获取班级信息
//            runThreadAction("3754873335");
            if (Env.getAppContext().isUpdata && Env.getAppContext().isCancleUpdate && !Env.getAppContext().isAutoUpdate) { //判断是否要升级
                startUpdate();
            }
            className.setText("正在查询绑定班级...");
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        isActivity = true;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(loginThread != null) loginThread.stopRun();
        if(modleThread != null)  modleThread.stopRun();
        if(backMainThread != null) backMainThread.stopRun();
    }

    /**
     * 结束获取信息的handle机制
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case H_SMainActivity.MSG_ONE:
                    Thread timeThread = new Thread(getTimeBySecondToView);
                    timeThread.start();
                    break;
                case H_SMainActivity.MSG_TWO:
                    if (mapList.size() > 1) {
                        Tvweather.setText(mapList.get(41).get("type") + "\t" + mapList.get(2).get("wendu") + " ℃");
                    } else {
                        Tvweather.setText("获取天气信息失败");
                    }
                    break;
                case H_SMainActivity.MSG_THREE:
                    isLockSet = true;
                    if (isLock) {
                        int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    } else {
                        int uiFlags = View.SYSTEM_UI_FLAG_VISIBLE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    }
                    isLockSet = false;
                    break;

                case H_SMainActivity.MSG_FOUR:
                    isNew = true;
                    if (!isScanCard) {
                        if (!isActivity) {
                            String code = mReception.replaceAll("\r", "").replaceAll("\n", "").trim();

                            if(!code.contains("\u0003\u0002")) {
                                isScanCard = true;
                                runThreadAction(code);
                                ToastUtil.showToast(V_MainActivity.this, "扫描学号：" + code, Toast.LENGTH_SHORT);
                            }else {
                                ToastUtil.showToast(V_MainActivity.this, "读卡失败，请不要一直刷卡，听到嘀一声就可以了");
                            }
                        }
                    } else {
                        ToastUtil.showToast(V_MainActivity.this, "正在通信中,不用再次刷卡");
                    }
                    break;
                case H_SMainActivity.MSG_FIVE:
                    //剩余时间的显示
                    if(Env.getAppContext().StudentId != null) {
                        if (time == 0) {
                            loginTime.setVisibility(View.GONE);
                            Env.getAppContext().StudentId = null;
                            if (!isActivity) selectLinear(0);
                            time = -1;
                        } else {
                            time--;
                            if (!isActivity) loginTime.setText(time + "");
                        }
                    }else{
                        loginTime.setVisibility(View.GONE);
                        time = -1;
                    }

                    break;
                case MSG_SIX:
                    //剩余时间的显示
                    if (backTime == 0) {
                        if (!isActivity) selectLinear(0);
                        backTime = -1;
                    } else {
                        backTime--;
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void runThreadAction() {
        super.runThreadAction();
    }

    @Override
    protected Object runThreadActionExceute() {
        super.runThreadActionExceute();
        return Env.getAppPresenter().getWeatherInfo("101270101");
//         101270101"101280101"
    }

    @Override
    protected void runThreadActionSuccess(final Object result) {
        super.runThreadActionSuccess(result);
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    mapList = getTimeAndWeatherUtil.getWeatherInfo((String) result);
                    Message msg = new Message();
                    msg.what = H_SMainActivity.MSG_TWO;
                    handler.sendMessage(msg);
                } catch (DocumentException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void runThreadActionError(Exception ex) {
        super.runThreadActionError(ex);
    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);

    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);
        if (actionName.equals("getClassInfo")) {
            return Env.getAppPresenter().getClassInfo(Env.getAppContext().carddevid);
        } else {
            return Env.getAppPresenter().login(actionName);
        }
    }

    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if (actionName.equals("getClassInfo")) {
            getClassInfoResponse response = (getClassInfoResponse) result;
            if (response.isSuccess()) {
                className.setText(response.ClassName);
            } else {
                className.setText(response.getErrMsg());
                ToastUtil.showToast(this, response.getErrMsg());
                className.setOnClickListener(getclassInfoListener);

            }
            selectLinear(0);
        } else{
            loginResponse response = (loginResponse) result;
            isScanCard = false;
            if (response.isSuccess()) {
                SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[5]);
                imageViews[5].startAnimation(animation);
                showFragment(5, 5);
                time = 90;
                loginTime.setText(time + "");
                loginTime.setVisibility(View.VISIBLE);
                loginTime.setText(time + "");
                Env.getAppContext().cardID =actionName ;
            } else {
                ToastUtil.showToast(this, response.getErrMsg());
            }
        }
    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                initControls();
                setListener();
                showFragment(0, 0);
                break;
            case 2:
                finish();
                break;
            default:
                break;
        }

    }

    @Override
    public void onClick(View view) {
        backTime = Env.getAppContext().backMainTime * 60;
        switch (view.getId()) {
            case R.id.home:
                backTime = -1;
                selectLinear(0);
                break;
            case R.id.home1:
                selectLinear(1);
                break;
            case R.id.home2:
                selectLinear(2);
                break;
            case R.id.home3:
                scrollView.arrowScroll(view.FOCUS_LEFT);
                selectLinear(3);
                break;
//            case R.id.home4:
//                selectLinear(4);
//                break;
            case R.id.home5:
                scrollView.arrowScroll(view.FOCUS_RIGHT);
                selectLinear(4);
                break;
            case R.id.home6:
                scrollView.arrowScroll(view.FOCUS_RIGHT);

                selectLinear(5);
                break;
            case R.id.home7:
                selectLinear(6);
                break;
            case R.id.home8:
                selectLinear(7);
                break;
            case R.id.home9:
                selectLinear(8);
                break;
            case R.id.home10:
                selectLinear(9);
                break;
        }
    }

    /**
     * 刷卡接收数据
     */
    private boolean isNew = true;
    private String mReception = "";
    @Override
    protected void onDataReceived(final byte[] buffer, final int size) {
        runOnUiThread(new Runnable() {
            public void run() {
                if (!TextUtils.isEmpty(Env.getAppContext().host)) {
                    if (mReception != null) {
                        if (isNew) {
                            isNew = false;
                            mReception = "";
                        }
                        mReception += (new String(buffer, 0, size));
                        handler.removeMessages(H_SMainActivity.MSG_FOUR);
                        handler.sendEmptyMessageDelayed(H_SMainActivity.MSG_FOUR, 1000);
                    }
                } else {
                    ToastUtil.showToast(V_MainActivity.this, "还没有设置端口号，请双击顶部栏去到设置界面");
                }
            }

        });

    }



    /**
     * 登录剩余时间监听
     */
    private class LoginThread extends Thread {

        private boolean stopFlag = false;

        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = H_SMainActivity.MSG_FIVE;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (!stopFlag);
        }

         /**
         * 通知线程需要停止
         */
         private void stopRun() {
            stopFlag = true;
        }
    };


    /**
     * 获取班牌当前模式
     */

    private boolean flag = true;
    private class ModleThread extends Thread {

        private boolean stopFlag = false;
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!isActivity) {
                    getClassTypeResponse response = Env.getAppPresenter().getClassType();
                    if (response.isSuccess()) {

                        if (!response.Value.equals("Common")) {
                            flag = false;
                            Env.getAppContext().type = response.Value;
                            Env.getAppContext().DevicePath = response.DevicePath;

                            Intent i = new Intent(V_MainActivity.this, A_LaunchActivity.class);
                            V_MainActivity.this.startActivity(i);
                        }
                    }
                }
            } while (flag && !isActivity && !stopFlag);
        }
        private void stopRun() {
            stopFlag = true;
        }
    };

    /**
     * 每秒获取系统时间
     */
    private Runnable getTimeBySecond = new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = H_SMainActivity.MSG_ONE;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    };
    private class BackMainThread extends Thread {

        private boolean stopFlag = false;
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = MSG_SIX;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (!stopFlag);
        }
        /**
         * 通知线程需要停止
         */
        private void stopRun() {
            stopFlag = true;
        }
    };
    /**
     * 获取系统时间并且渲染在视图
     */
    private Runnable getTimeBySecondToView = new Runnable() {
        @Override
        public void run() {
            final String data = getTimeAndWeatherUtil.getTimeAndData();
            final String[] value = data.split("-");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Tvtime.setText(value[1]);
                    Tvdate.setText(value[0] + "\t" + value[2]);
                }
            });
        }
    };

    /**
     * 点击按钮切换fragment
     */
    private void showFragment(int index, int currentIndex) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        // 动作1:隐藏当前
        transaction.hide(fragments[currentShowFragmentIndex]);
        Fragment showFragment = null;
        // 动作2:添加要显示的
        if (currentIndex == 5) {
            showFragment = new V_AttendableFragment();
        } else if (currentIndex == 0) {
            showFragment = new V_HomeFragment();
        } else {
            showFragment = fragments[index];
        }
        if (!showFragment.isAdded()) {
            transaction.replace(R.id.fragmentP, showFragment);
        }
        // 动作3:显示出来
        transaction.show(showFragment);
        // 提交事务
        transaction.commit();
        currentShowFragmentIndex = index;

    }

    /**
     * 点击按钮开始动画
     */
    public void selectLinear(int i) {
        if (!Env.getAppContext().host.equals("")) {
            SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[i]);
            imageViews[i].startAnimation(animation);
            showFragment(i, 10);

        } else {
            ToastUtil.showToast(this, "还没有设置端口号，请双击顶部栏去到设置界面");
        }
    }

    /**
     * 启动时按钮动画
     */
    private void startAnim() {
        int duration = 500;
        for (int i = 0; i < linearLayouts.length; i++) {
            Animation animation1 = AnimationUtils.loadAnimation(V_MainActivity.this, R.anim.buttom_start_anim);
            animation1.setDuration(duration);
            linearLayouts[i].startAnimation(animation1);
            duration += 200;
        }
    }

    /**
     * 双击操作
     */

    private LinearLayout[] linearLayout = new LinearLayout[2]; // 进入设置界面弹出的dialog的按钮
    private EditText pass; //输入密码框
    private OnDoubleClickListener onDoubleClickListener = new OnDoubleClickListener(
            new OnDoubleClickListener.DoubleClickCallback() {
                @Override
                public void onDoubleClick() {

                    final H_SettingDailog dailog = new H_SettingDailog(V_MainActivity.this);
                    linearLayout = dailog.getBtnView();
                    linearLayout[0].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            pass = dailog.getPass();
                            if (!TextUtils.isEmpty(pass.getText().toString()) && pass.getText().toString().equals(Env.getAppContext().password)) {
                                dailog.closeDialog();
                                startActivityForResult(new Intent(V_MainActivity.this, H_SettingActivity.class), 1);
                            } else {
                                ToastUtil.showToast(V_MainActivity.this, "密码错误");
                                pass.setText("");
                            }
                        }
                    });
                    linearLayout[1].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dailog.closeDialog();
                        }
                    });
                    dailog.showDialog();

                }

            });


    /**
     * 升级安装包
     */

    private LinearLayout[] btns = new LinearLayout[2];
    private TextView textView;

    private void startUpdate() {
        final V_UpdateDailog dailog = new V_UpdateDailog(V_MainActivity.this);
        btns = dailog.getBtnView();
        textView = dailog.getTextView();

        dailog.showDialog();
        textView.setText(Env.getAppContext().updateTip);

        btns[1].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Env.getAppContext().isCancleUpdate = false;
                dailog.closeDialog();
            }
        });

        btns[0].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Env.getAppContext().isCancleUpdate = false;
                DownFileUtil.downloadFile(V_MainActivity.this);
                dailog.closeDialog();
            }
        });
    }

    private View.OnClickListener getclassInfoListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(className.getText().toString().equals("班级获取失败，请点击重试")){
                className.setText("正在查询绑定班级...");
                runThreadAction("getClassInfo"); //获取班级信息

            }

        }
    };



}